import Layout from '@/layout'
import { pageMap, pageIndex, router404 } from '@/router'

const state = {
    routes: [],
    routesList: [],
    hasGetRoutesApi: false
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = routes
    },
    SET_ROUTES_LIST: (state, routerList) => {
        state.routesList = routerList
    },
    SET_hasGetRoutesApi: (state, hasGetRoutesApi) => {
        state.hasGetRoutesApi = hasGetRoutesApi
    }
}

const actions = {
    clearPermission_routes({ commit }) {
        commit('SET_ROUTES', [])
        commit('SET_hasGetRoutesApi', false)
    },
    generateRoutes({ commit }, { menuList }) {
        return new Promise(resolve => {
            let asyncRouter = [{
                path: '/',
                component: Layout,
                children: []
            }]

            function getChild(list) {
                list.forEach(item => {
                    if (item.uri) {
                        asyncRouter[0].children.push({
                            path: item.uri,
                            component: pageMap[item.uri],
                            name: item.uri,
                            meta: { title: item.name, icon: item.icon, affix: false, activeMenu: item.levelIds }
                        })
                    }
                    item.meta = { title: item.name, icon: item.icon, affix: false, activeMenu: item.levelIds }
                    if (item.children && item.children.length === 0) {
                        delete item.children
                    }
                    if (item.children && item.children.length > 0) {
                        getChild((item.children))
                    }
                })
            }
            menuList.forEach(item => {
                if (item.children && item.children.length === 0) {
                    delete item.children
                } else {
                    getChild(item.children)
                }
                item.meta = { title: item.name, icon: item.icon, affix: false, activeMenu: item.levelIds }
            })
            commit('SET_ROUTES', menuList)
            commit('SET_hasGetRoutesApi', true)
            const routerList = asyncRouter.concat(pageIndex).concat(router404)
            commit('SET_ROUTES_LIST', routerList)
            resolve(routerList)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
